import http from '@ohos.net.http';
import HttpResponse from './HttpResponse';

export function requestHttp(url: string, methods: http.RequestMethod, headers: Object = "", data?: any): Promise<HttpResponse> {
  //hostname /todos/2
  const BASE_URL: string = "https://jsonplaceholder.typicode.com";
  let httpRequest = http.createHttp();
  let responseResult = httpRequest.request(BASE_URL + url, {
    method: methods,
    header: headers,
    extraData: (data === null || data == undefined) ? "" : JSON.stringify(data),
  });
  let response = new HttpResponse();
  return responseResult.then((res => {
    if (res.responseCode == 200) {
      let httpRes: HttpResponse = JSON.parse(`${res.result}`);
      response.data = httpRes.data;
      response.code = httpRes.code;
      response.message = httpRes.message;
    } else {
      response.message = '请求错误';
      response.code = 400;
    }
    return response;
  })).catch(() => {
    response.message = '请求错误';
    response.code = 400;
    return response;
  });
}